package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoradService;
import com.example.forum.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/article")
@Api(tags = "文章管理接口")
@Slf4j
public class ArticleAdminController {

    @Resource
    private IArticleService articleService;
    
    @Resource
    private IUserService userService;
    
    @Resource
    private IBoradService boardService;
    
    @ApiOperation("分页获取文章列表")
    @GetMapping("/list")
    public AppResult getAllArticles(HttpServletRequest request,
                                    @RequestParam(value = "page", defaultValue = "1") int page,
                                    @RequestParam(value = "size", defaultValue = "10") int size,
                                    @RequestParam(value = "keyword", required = false) String keyword,
                                    @RequestParam(value = "category", required = false) String category,
                                    @RequestParam(value = "status", required = false) String status,
                                    @RequestParam(value = "sort", defaultValue = "createTime") String sort,
                                    @RequestParam(value = "order", defaultValue = "desc") String order) {
        // 验证管理员权限
        if (!isAdmin(request)) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        
        try {
            // 使用分页服务获取文章
            Map<String, Object> result = articleService.getArticlesByPage(page, size, keyword, status, sort, order);
            
            return AppResult.success(result);
        } catch (Exception e) {
            log.error("获取文章列表失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    @ApiOperation("更新文章状态")
    @PostMapping("/status")
    public AppResult<Void> updateArticleStatus(
            HttpServletRequest request,
            @RequestParam("articleId") Long articleId,
            @RequestParam("state") Byte state) {
        
        // 验证管理员权限
        if (!isAdmin(request)) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        
        // 参数校验
        if (articleId == null || (state != 0 && state != 1)) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        
        try {
            articleService.updateArticleState(articleId, state);
            return AppResult.success();
        } catch (Exception e) {
            log.error("更新文章状态失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    @ApiOperation("删除文章")
    @PostMapping("/delete")
    public AppResult<Void> deleteArticle(
            HttpServletRequest request,
            @RequestParam("articleId") Long articleId) {
        
        // 验证管理员权限
        if (!isAdmin(request)) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        
        // 参数校验
        if (articleId == null) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        
        try {
            articleService.adminDeleteArticle(articleId);
            return AppResult.success();
        } catch (Exception e) {
            log.error("删除文章失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    /**
     * 获取文章数量统计
     * @param request HTTP请求，用于获取Session
     * @return 文章统计信息，包含total和today两个字段
     */
    @ApiOperation("获取文章数量统计")
    @GetMapping("/count")
    public AppResult getArticleCount(HttpServletRequest request) {
        // 验证管理员权限
        if (!isAdmin(request)) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        
        Map<String, Object> countMap = new HashMap<>();
        // 获取总文章数
        int totalArticles = articleService.countTotalArticles();
        // 获取今日新增文章数
        int todayNewArticles = articleService.countTodayNewArticles();
        
        countMap.put("total", totalArticles);
        countMap.put("today", todayNewArticles);
        
        return AppResult.success(countMap);
    }
    
    /**
     * 置顶/取消置顶文章
     * @param request HTTP请求，用于获取Session
     * @param articleId 文章ID
     * @param isPinned 是否置顶 (1置顶, 0取消置顶)
     * @return 操作结果
     */
    @ApiOperation("置顶/取消置顶文章")
    @PostMapping("/pin")
    public AppResult togglePinArticle(
            HttpServletRequest request,
            @RequestParam("articleId") Long articleId,
            @RequestParam("isPinned") Byte isPinned) {
        
        // 验证管理员权限
        if (!isAdmin(request)) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        
        // 参数校验
        if (articleId == null || (isPinned != 0 && isPinned != 1)) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        
        try {
            // 调用服务更新文章置顶状态
            articleService.updateArticlePinState(articleId, isPinned);
            return AppResult.success();
        } catch (Exception e) {
            log.error("更新文章置顶状态失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    /**
     * 辅助方法：检查当前用户是否为管理员
     * @param request HTTP请求
     * @return 是否为管理员
     */
    private boolean isAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return false;
        }
        
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        return user != null && user.getIsAdmin() == 1;
    }
} 